<template>
  <el-divider content-position="center"
    ><span style="font-size: 23px; font-family: '楷体'">管理员管理</span></el-divider
  ><br />
  <!-- 搜索栏 -->
  <el-form :inline="true">
    <el-form-item label="用户名">
      <el-input
        v-model="searchUsername"
        type="text"
        autocomplete="off"
        style="width: 300px"
        placeholder="输入搜索用户名"
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="getAdminInfoList()">查询</el-button>
      <el-button type="info" @click="clearSearch()">重置</el-button>
    </el-form-item>
    <span style="margin-left: 670px; font-size: small; color: rgba(97, 88, 88, 0.5)"
      >普通管理员无以下权限</span
    >
  </el-form>
  <div style="float: right; margin-right: 7%; margin-bottom: 20px">
    <el-button
      :disabled="isSuperSignValue"
      style="width: 110px"
      type="success"
      @click="toAddAdmin()"
      >+&nbsp;&nbsp;新增</el-button
    >
  </div>
  <!-- 列表 -->
  <el-table :data="adminInfoList" border>
    <el-table-column prop="username" label="账号" align="center" />
    <el-table-column prop="superSign" label="管理员类型" width="200px" align="center">
      <template v-slot="scope">
        <span v-if="scope.row.superSign === 1">超级管理员</span>
        <span v-if="scope.row.superSign === 0">普通管理员</span>
      </template>
    </el-table-column>
    <el-table-column prop="ban" label="是否启用" width="100px" align="center">
      <template v-slot="scope">
        <span v-if="scope.row.ban === 1">启用</span>
        <span v-if="scope.row.ban === 0">禁用</span>
      </template>
    </el-table-column>
    <el-table-column prop="createTime" label="创建时间" sortable align="center" />
    <el-table-column prop="updateTime" label="修改时间" sortable align="center" />
    <el-table-column prop="" label="操作" align="center">
      <template #default="{ row }">
        <el-button :disabled="isSuperSignValue" type="primary" @click="toEditAdminInfo(row)"
          >编辑</el-button
        >
        <el-button :disabled="isSuperSignValue" type="danger" @click="deleteAdmin(row)"
          >删除</el-button
        >
      </template>
    </el-table-column>
  </el-table>

  <!-- 添加管理员弹窗 -->
  <el-dialog
    v-model="dialogFormVisible"
    :title="dialogTitle"
    style="width: 30%"
    center
    align-center
  >
    <el-form ref="addAdminInfoRulesRef" :rules="addAdminInfoRules" :model="adminInfo">
      <el-form-item label="账号" prop="username" label-width="90px">
        <el-input
          :disabled="nameDisabled"
          v-model="adminInfo.username"
          placeholder="请输入账号"
          style="width: 250px"
          autocomplete="off"
        />
      </el-form-item>
      <el-form-item :label="columPwd" prop="password" label-width="90px">
        <el-input
          v-model="adminInfo.password"
          type="password"
          placeholder="请输入密码"
          style="width: 250px"
          autocomplete="off"
        />
      </el-form-item>
      <el-form-item :label="columRePwd" prop="confirmPassword" label-width="90px">
        <el-input
          v-model="adminInfo.confirmPassword"
          type="password"
          placeholder="请再次输入密码"
          style="width: 250px"
          autocomplete="off"
        />
      </el-form-item>
      <el-form-item label="管理员类型" prop="superSign">
        <el-select v-model="adminInfo.superSign" placeholder="请选择" style="width: 250px">
          <el-option label="超级管理员" value="1" />
          <el-option label="普通管理员" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="使用状态" prop="ban" label-width="90px">
        <el-select v-model="adminInfo.ban" placeholder="请选择" style="width: 250px">
          <el-option label="启用" value="1" />
          <el-option label="禁用" value="0" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="
            dialogTitle === '添加管理员'
              ? submitAddAdmin(addAdminInfoRulesRef)
              : SubmitEditAdminInfo(addAdminInfoRulesRef)
          "
          >确认</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import {
  ElMessage,
  ElMessageBox,
  type FormInstance,
  type FormRules,
  type FormProps
} from 'element-plus'
import {
  getAdminInfoListService,
  addAdminService,
  editAdminService,
  deleteAdminService
} from '@/apis/adminManage'
import { adminStore } from '@/stores/admin'
const dialogFormVisible = ref(false)
const searchUsername = ref('')
const dialogTitle = ref('')
const columPwd = ref('')
const columRePwd = ref('')
const nameDisabled = ref(true)
const isSuperSignValue = ref(true)
const adminstore = adminStore()
//查询管理员

//清空搜索栏
const clearSearch = () => {
  searchUsername.value = ''
  getAdminInfoList()
}
const adminInfo = ref({
  username: '',
  password: '',
  confirmPassword: '',
  superSign: '',
  ban: ''
})
const adminInfoList = ref([])

onMounted(() => {
  getAdminInfoList()
  isSuperSign()
})

//查询管理员列表
const getAdminInfoList = async () => {
  console.log(searchUsername.value)
  let result = await getAdminInfoListService(searchUsername.value)
  if (result.data.code === 1) {
    console.log(result.data.data)
    adminInfoList.value = result.data.data
  } else {
    ElMessage.error('页面载入失败')
  }
}

// 校验确认密码
const checkPassword = (rule: any, value: any, callback: any) => {
  if (dialogTitle.value === '添加管理员' && value === '') {
    callback(new Error('请输入密码'))
  } else {
    callback()
  }
}
const checkRePassword = (rule: any, value: any, callback: any) => {
  if (adminInfo.value.password != '' && value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value != adminInfo.value.password) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}
// 注册验证规则
const addAdminInfoRulesRef = ref<FormInstance>()
const addAdminInfoRules = reactive<FormRules<typeof adminInfo>>({
  username: [{ required: true, message: '请填写用户名', trigger: 'change' }],
  password: [{ validator: checkPassword, trigger: 'change' }],
  confirmPassword: [{ validator: checkRePassword, trigger: 'change' }],
  superSign: [{ required: true, message: '请选择管理员类型', trigger: 'change' }],
  ban: [{ required: true, message: '请选择管理员状态', trigger: 'change' }]
})

//清空添加的数据
const clearAdminInfo = () => {
  adminInfo.value.username = ''
  adminInfo.value.password = ''
  adminInfo.value.confirmPassword = ''
  adminInfo.value.superSign = ''
  adminInfo.value.ban = ''
}
//添加管理员
const toAddAdmin = () => {
  nameDisabled.value = false
  dialogFormVisible.value = true
  dialogTitle.value = '添加管理员'
  columPwd.value = '密码'
  columRePwd.value = '确认密码'
  clearAdminInfo()
}
const submitAddAdmin = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      console.log(adminInfo.value)
      console.log('添加')
      addAdminService(adminInfo.value).then((result) => {
        if (result.data.code === 1) {
          ElMessage.success('添加成功')
          clearAdminInfo()
          getAdminInfoList()
        } else {
          ElMessage.error(result.data.msg ? result.data.msg : '操作失败')
        }
      })
      dialogFormVisible.value = false
    } else {
      ElMessage.error('请正确填写相关信息再提交')
      return false
    }
  })
}
//编辑管理员
const toEditAdminInfo = (row: any) => {
  nameDisabled.value = true
  dialogFormVisible.value = true
  dialogTitle.value = '编辑管理员'
  columPwd.value = '更新密码(非必须)'
  columRePwd.value = '确认更新密码'
  console.log(row)
  adminInfo.value.username = row.username
  if (row.superSign === 1) {
    adminInfo.value.superSign = '超级管理员'
  } else {
    adminInfo.value.superSign = '普通管理员'
  }
  if (row.ban === 1) {
    adminInfo.value.ban = '启用'
  } else {
    adminInfo.value.ban = '禁用'
  }
}
const SubmitEditAdminInfo = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      adminInfo.value.superSign === '超级管理员' || adminInfo.value.superSign === '1'
        ? (adminInfo.value.superSign = 1)
        : (adminInfo.value.superSign = 0)
      adminInfo.value.ban === '启用' || adminInfo.value.ban === '1'
        ? (adminInfo.value.ban = 1)
        : (adminInfo.value.ban = 0)
      editAdminService(adminInfo.value).then((result) => {
        if (result.data.code === 1) {
          ElMessage.success('修改成功')
          clearAdminInfo()
          getAdminInfoList()
        } else {
          ElMessage.error(result.data.msg ? result.data.msg : '操作失败')
        }
      })
      dialogFormVisible.value = false
    } else {
      ElMessage.error('请正确填写相关信息再提交')
      return false
    }
  })
}

//删除管理员
const deleteAdmin = (row: any) => {
  ElMessageBox.confirm('是否删除管理员 ' + row.username, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      console.log(row.username)
      deleteAdminService(row.username).then((result) => {
        if (result.data.code === 1) {
          ElMessage.success('删除成功')
          clearAdminInfo()
          getAdminInfoList()
        } else {
          ElMessage.error(result.data.msg ? result.data.msg : '操作失败')
        }
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除'
      })
    })
}
//非超级管理员禁用功能
const isSuperSign = async () => {
  let result = await getAdminInfoListService(adminstore.adminInfo.username)
  for (let index = 0; index < result.data.data.length; index++) {
    const superSigns = result.data.data[index].superSign
    console.log('super:' + superSigns)
    if (superSigns === 1) {
      isSuperSignValue.value = false
    }
  }
}
</script>
